﻿using ProtoBuf.Message;
using System.Collections;
using System.Collections.Generic;
using UI;
using UnityEngine;
using UnityEngine.UI;
using Yunchang;
using Yunchang.NetworkLayer;
using System;
public class SliderData
{
    public int startExp;
    public int endExp;

    public int backExp;//背景Exp

    public bool isMax = false;
    public float sliderSpeed = 0;
    public bool isUpOrDown = false; //是升段还是将
    public Table.DataModel.TableAutoChessGrade endNextrade;
}
public class GradeScoreSlider
{
    private SliderData sliderData;
    private Action<float,int,int,bool> onSliderUpdate;
    private Action<Table.DataModel.TableAutoChessGrade,int,int> onSliderEnd;

    private int _ExpValue = 0;
    private float _sliderSpeed = 0;
    public void InitSlider(SliderData data,Action<float,int, int, bool> onUpdate,Action<Table.DataModel.TableAutoChessGrade,int,int> onEnd)
    {
        this.sliderData = data;
        this.onSliderUpdate = onUpdate;
        this.onSliderEnd = onEnd;
        _ExpValue = sliderData.startExp;
        _sliderSpeed = sliderData.sliderSpeed;
    }

    public bool IsFinished()
    {
        return _ExpValue == sliderData.endExp;
    }

    public void TickSlider()
    {
        if (_ExpValue != sliderData.endExp)
        {
            if (_sliderSpeed >= 0)
            {
                _sliderSpeed -= Time.deltaTime;
                return;
            }
            _sliderSpeed = sliderData.sliderSpeed;

            if (sliderData.startExp <= sliderData.endExp)//增加
            {
                _ExpValue++;
                var curSlider = _ExpValue * 1f / sliderData.backExp;
                if (onSliderUpdate != null)
                {
                    onSliderUpdate(curSlider, _ExpValue, sliderData.backExp, sliderData.isMax);
                }
            }
            else //减少
            {
                _ExpValue--;
                var curSlider = _ExpValue * 1f / sliderData.backExp;
                if (onSliderUpdate != null)
                {
                    onSliderUpdate(curSlider, _ExpValue, sliderData.backExp, sliderData.isMax);
                }
            }
        }
        else
        {
            if (onSliderEnd != null)
            {
                onSliderEnd(sliderData.endNextrade, _ExpValue, sliderData.backExp);
            }
        }
    }
}
public class AutoChessDuanPage : OPPage
{
    public Text title, subGrade, rangExp, curExp;
    public TextureKit gradImage;
    public GroupSpriteKit gradTitleImage;
    public LabelNumRoll rollLable;
    public GameObject MaxRoot,NormalRoot;
    public Text maxText;

    private SCAutoChessScoreChange data;
    private Table.DataModel.TableAutoChessGrade beforeGrade,afterGrade;

    private ParticleSystem particle;
    public Transform effectRoot,duanWeiRoot;
    private CommonEffect effect,duanEffect;

    public float delateDuanChangeEffectTime_0 = 1f;
    public float delateEffectTime_1 = 1f;
    protected override void DoOpen()
    {
        base.DoOpen();
        // data = Params as SCAutoChessScoreChange;
        data = AutoChess.AutoChessManager.Ins.cacheData.overScoreData;
        if (data == null)
        {
            ClosePage();
            return;
        }
        int selfRank = 1;
        foreach (var item in data.reportInfos)
        {
            if (item.playerId == StaticData.playerData.playerId)
            {
                selfRank = item.rank;
            }
        }

        title.text = Table.Blo.AutoChessBlo.GetPlayerRankTitle(selfRank);
        effect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.UI_150_zizhouqi_quan, effectRoot, (obj) => {
            particle = obj.transform.GetComponentInChildren<ParticleSystem>();
            particle.gameObject.AddMissingComponent<UGUISortingOrder>();
            StartLogic();
        });
    }
    private void ClosePage()
    {
        Close();
        AutoChessFieldViewCtr.Ins.OpenResultListPage();
    }

    public int _beforeGrade = 1;
    public int _afterGrade = 1;
    public int _beforeScore = 0;
    public int _afterScore = 11;
    public int _addScore = 11;
    public void TestShowGradePage()
    {
        var data = new SCAutoChessScoreChange();
        data.beforeGrade = _beforeGrade;
        data.beforeScore = _beforeScore;
        data.afterGrade = _afterGrade;
        data.afterScore = _afterScore;
        data.changeScore = _addScore;
        this.data = data;
        if (effect != null)
        {
            effect.Clear();
        }
        if (duanEffect != null)
        {
            effect.Clear();
        }
        effect = CommonEffectManager.Instance.PlayEffectImmediate(CommonEffectResId.UI_150_zizhouqi_quan, effectRoot, (obj) => {
            particle = obj.transform.GetComponentInChildren<ParticleSystem>();
            particle.gameObject.AddMissingComponent<UGUISortingOrder>();
            StartLogic();
        });
    }

    private void StartLogic()
    {
        beforeGrade = Table.Blo.AutoChessBlo.GetGradeById(data.beforeGrade);
        afterGrade = Table.Blo.AutoChessBlo.GetGradeById(data.afterGrade);

        if (beforeGrade == null || afterGrade == null)
        {
            ClosePage();
            return;
        }

        SetGradeInfo(beforeGrade, data.beforeScore - beforeGrade.minScore, beforeGrade.maxScore+1 - beforeGrade.minScore);

        var maxLevel = Table.Blo.AutoChessBlo.GetMaxGradeLevel();
        if (data.beforeGrade == maxLevel)
        {
            MaxRoot.SetActive(true);
            NormalRoot.SetActive(false);
            curExp.text = string.Format("{0}", data.beforeScore - beforeGrade.minScore); //当前经验
            maxText.text = "+" + (data.beforeScore - beforeGrade.minScore);
        }
        else
        {
            MaxRoot.SetActive(false);
            NormalRoot.SetActive(true);
        }
        StartCoroutine(StartNumEffect());
    }
    protected override void DoClose(bool immediately)
    {
        base.DoClose(immediately);
        AutoChessFieldViewCtr.Ins.OpenResultListPage();
    }
    private void SetEffectValue(float value)
    {
        particle.GetComponent<Renderer>().material.SetFloat("_kongzhi", value);
    }
    private void SetGradeInfo(Table.DataModel.TableAutoChessGrade curGrade,int curExpValueStart, int endExpBack)
    {
        var maxLevel = Table.Blo.AutoChessBlo.GetMaxGradeLevel();
        if (data.afterGrade == maxLevel)
        {
            MaxRoot.SetActive(true);
            NormalRoot.SetActive(false);
        }
        else
        {
            MaxRoot.SetActive(false);
            NormalRoot.SetActive(true);
        }

        gradImage.TextureName = curGrade.gradeIcon; //图标
        gradTitleImage.SetSpriteName(curGrade.gradeTextIcon);//文字图标
        subGrade.text = curGrade.subGradeType.ToString();  //子段位
        curExp.text = string.Format("{0}<color=white>/{1}</color>", curExpValueStart , endExpBack);//当前经验
        rangExp.text = data.changeScore > 0 ? "+"+data.changeScore.ToString() :string.Format("<color=#ff2a00>{0}</color>", data.changeScore);

        if (maxLevel == curGrade.grade)
        {
            SetEffectValue(1);
        }
        else
        {
            SetEffectValue(curExpValueStart * 1f / endExpBack);
        }
    }

    IEnumerator StartNumEffect()
    {
        var allSlider = GetSliderObjects();
        SliderData curSlider = allSlider[0];
        allSlider.RemoveAt(0);
        GradeScoreSlider gradeSlider = new GradeScoreSlider();
        gradeSlider.InitSlider(curSlider, OnUpdateSlider, OnEndSlider);
        while (curSlider != null)
        {
            if (!gradeSlider.IsFinished())
            {
                gradeSlider.TickSlider();
                if (gradeSlider.IsFinished())
                {
                    if (allSlider.Count > 0)
                    {
                        duanEffect = CommonEffectManager.Instance.PlayEffectImmediate(
                        allSlider[0].isUpOrDown ? CommonEffectResId.AC_UI_UI_150_zizhouqi_quanbaoJiang :
                        CommonEffectResId.AC_UI_UI_150_zizhouqi_quanbaoJiang, duanWeiRoot);
                    }
                    yield return new WaitForSeconds(delateDuanChangeEffectTime_0); //等特效完全播完
                    gradeSlider.TickSlider();
                }
                yield return 1;
            }
            else
            {
                if (allSlider.Count > 0)
                {
                    curSlider = allSlider[0];
                    allSlider.RemoveAt(0);
                    gradeSlider = new GradeScoreSlider();
                    gradeSlider.InitSlider(curSlider, OnUpdateSlider, OnEndSlider);
                    yield return new WaitForSeconds(delateEffectTime_1); //等特效完全播完
                }
                else
                {
                    curSlider = null;
                }
            }
        }
    }

    private void OnUpdateSlider(float sliderValue,int curScore,int maxScroe,bool isMaxLevel)
    {
        if (isMaxLevel)
        {
            SetEffectValue(1f);
            maxText.text = "+" + curScore;
        }
        else
        {
            SetEffectValue(curScore * 1f / maxScroe);
            curExp.text = string.Format("{0}<color=white>/{1}</color>", curScore, maxScroe);//当前经验
        }
       
    }

    private void OnEndSlider(Table.DataModel.TableAutoChessGrade grade,int onEndExpValue,int endExpBack)
    {
       
        SetGradeInfo(grade, onEndExpValue, endExpBack);
    }
    public List<SliderData> GetSliderObjects()
    {
        AutoChess.UtilityHelper.PlayUIAudio("AC_addRankExp");
        var speed = 1.5f / data.changeScore;
        var maxLevel = Table.Blo.AutoChessBlo.GetMaxGradeLevel();
        beforeGrade = Table.Blo.AutoChessBlo.GetGradeById(data.beforeGrade);
        afterGrade = Table.Blo.AutoChessBlo.GetGradeById(data.afterGrade);
        List<SliderData> sliders = new List<SliderData>();
        if (data.beforeGrade != data.afterGrade)
        {
            if (data.beforeGrade < data.afterGrade)//升
            {
                var tempData = new SliderData();
                tempData.sliderSpeed = speed;
                tempData.isMax = data.beforeGrade == maxLevel;
                tempData.startExp = data.beforeScore - beforeGrade.minScore;//升开始也不会有 最大等级情况
                tempData.endExp = beforeGrade.maxScore + 1 - beforeGrade.minScore;
                tempData.backExp = beforeGrade.maxScore + 1 - beforeGrade.minScore;
                tempData.endNextrade = afterGrade;//结束的回调
                tempData.isUpOrDown = true;
                sliders.Add(tempData);

                tempData = new SliderData();
                tempData.sliderSpeed = speed;
                tempData.isMax = data.afterGrade == maxLevel;
                if (!tempData.isMax)
                {
                    tempData.startExp = 0;
                    tempData.endExp = data.afterScore - afterGrade.minScore;
                }
                else
                {
                    tempData.startExp = 0;
                    tempData.endExp = data.afterScore - afterGrade.minScore;
                }
                tempData.backExp = afterGrade.maxScore + 1 - afterGrade.minScore;
                tempData.endNextrade = afterGrade;
                tempData.isUpOrDown = true;
                sliders.Add(tempData);
            }
            else    //降
            {
                var tempData = new SliderData();
                tempData.sliderSpeed = speed;
                tempData.isMax = data.beforeGrade == maxLevel;
                if (!tempData.isMax)
                {
                    tempData.startExp = data.beforeScore - beforeGrade.minScore;
                    tempData.endExp = 0;
                }
                else
                {
                    tempData.startExp = data.beforeScore - beforeGrade.minScore;
                    tempData.endExp = 0;
                }
                tempData.backExp = beforeGrade.maxScore　+ 1 - beforeGrade.minScore;
                tempData.endNextrade = afterGrade;
                tempData.isUpOrDown = false;
                sliders.Add(tempData);

                tempData = new SliderData();
                tempData.sliderSpeed = speed;
                tempData.isMax = data.afterGrade == maxLevel;
                tempData.startExp = afterGrade.maxScore + 1 - afterGrade.minScore;//降 第二段 不会有最大等级情况
                tempData.endExp = data.afterScore - afterGrade.minScore;
                tempData.backExp = afterGrade.maxScore + 1 - afterGrade.minScore;
                tempData.endNextrade = afterGrade;
                tempData.isUpOrDown = false;
                sliders.Add(tempData);
            }
        }
        else
        {
            var tempData = new SliderData();
            tempData.sliderSpeed = speed;
            tempData.isMax = data.afterGrade == maxLevel;
            if (!tempData.isMax)
            {
                tempData.startExp = data.beforeScore - beforeGrade.minScore;
                tempData.endExp = data.afterScore - afterGrade.minScore;
            }
            else
            {
                tempData.startExp = data.beforeScore - beforeGrade.minScore;
                tempData.endExp = data.afterScore - afterGrade.minScore;
            }
            
            tempData.backExp = afterGrade.maxScore + 1 - afterGrade.minScore;
            tempData.endNextrade = afterGrade;
            sliders.Add(tempData);
        }
        return sliders;
    }
}
